<?php


namespace App\Admin\Extensions\Form;

use Dcat\Admin\Admin;
use Dcat\Admin\Form\Field;

class TableExtend extends Field
{
    protected $view = 'admin.form.table-extend';


    public function render()
    {
        if (! $this->shouldRender()) {
            return '';
        }

        Admin::style(
            <<<'CSS'
.table-has-many .fields-group .form-group {
    margin-bottom:0;
}
.table-has-many .fields-group .form-group .remove {
    margin-top: 10px;
}
CSS
        );
        Admin::script(
            <<<JS
(function () {
  
  $('#{$this->column}').on('click', '.{$this->column}-sub-delete', function () {
    $(this).closest('.{$this->column}-sub-item').remove();
  });
  $('#{$this->column}').on('click', '.{$this->column}-add', function () {
    var key = $(this).data('key-next');
    
    $(this)
      .parents('.{$this->column}-wrapper')
      .find('.{$this->column}-list')
      .append(
        $('template#{$this->column}-template').html()
          .replace(/__KEY__/g, key)
          
      );
    $(this).data('key-next', key + 1)
  });
  $('#{$this->column}').on('click', '.{$this->column}-delete', function () {
    $(this).closest('.{$this->column}-item').remove();
  });
})();
JS
        );
        $this->addVariables([
            'data' => $this->value(),
        ]);
        return parent::render();
    }
}
